const express = require("express")
const bodyParser = require("body-parser");
const {userpas} = require("./model/user");
const app = express();
const jwt = require("jsonwebtoken")
app.listen(8081,function(){
    console.log("开启服务")
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))


app.all("*",function(req,res,next){   
    res.header("Access-Control-Allow-Origin","*");    
    res.header("Access-Control-Allow-Headers","content-type,Authorization");   
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");    
    if (req.method.toLowerCase() == 'options')
        res.send(200);  
    else
        next();
})
app.post("/login",function(req,res,next){
    let {username,password} = req.body
    userpas.findOne({
        username,
        password
    }).then(response=>{
        if(!response){//没有找到的
            res.send({ //登录失败
                fail:1
            })
        }else{
            let token = jwt.sign(
                {
                    username
                },
                "123456",
                {
                    expiresIn:60*60*24
                })  
            res.send({//登录成功
                fail:0,
                token:"Bearer "+token
            })
        } 
    })
})
app.post("/register",function(req,res,next){
    let {username,password} = req.body;
    userpas.findOne({
        username
    }).then(resp=>{
        //resp有值,则表示已注册
        if(resp){
            res.send({
                registerStatus:0
            })
            return;
        }else{
            //resp有值,则表示未注册
            userpas.create({
                username,
                password
            }).then(response=>{
                res.send({
                    registerStatus:1
                })
                return;
            })
        }
    })
})
function checkToken(req,res,next){
    //获取到前端发送请求的token
    let reqToken = req.headers.authorization;
    reqToken = reqToken.split(" ")[1]
    try{
        //利用verify进行解码,如果解码不出来则返回res.json中的内容
        let detoken =  jwt.verify(reqToken,"123456")
        console.log(detoken)

        next()
    }catch{
        res.json({
            code:0,
            message:"您没得权限访问哦"
        })
    }
}

app.get("/admin",checkToken,function(req,res,next){
   res.send("hello admin")
})